<template>
     <el-form :model="form" label-width="80px" class="form" :rules="rules" ref="form" clearable>
        <el-form-item label="出发城市" prop="departCity">
            <!-- fetch-suggestions 返回输入建议的方法 -->
            <!-- select 点击选中建议项时触发 -->
            <el-autocomplete v-model="form.departCity" placeholder="请搜索出发城市"
            :fetch-suggestions="queryDepartSearch"
            @select="handleDepartSelect"
            :trigger-on-focus="false" 
            :highlight-first-item ="true"
            @focus="clearMsg('departCity')"
            ></el-autocomplete>
        </el-form-item>
        <el-form-item label="到达城市" prop="destCity">
            <el-autocomplete v-model="form.destCity" placeholder="请搜索到达城市"
            :fetch-suggestions="queryDestSearch"
            @select="handleDestSelect"
            :trigger-on-focus="false"
            :highlight-first-item ="true"
            @focus="clearMsg('destCity')"
            ></el-autocomplete>
        </el-form-item>
        <el-form-item label="出发时间" prop="departDate">
            <el-date-picker
                v-model="form.departDate"
                type="date"
                placeholder="请选择日期"
                value-format="yyyy-MM-dd"
                @focus="clearMsg('departDate')"
                >
            </el-date-picker>
        </el-form-item>
        <el-button type="primary" class="btn" @click="search"><i class="el-icon-search"></i>搜索</el-button>
        <!-- 小块 -->
        <div class="link">
            <span @click="handleChange">换</span>
        </div>
    </el-form>
</template>

<script>
export default {
    data() {
      return {
        form: {
          departCity: '',
          departCode:'',
          destCity: '',
          destCode:'',
          departDate: ''
        },
        rules:{
            departCity:[
                {required:true,message:'请输入出发城市',trigger:'blur'}
            ],
            destCity:[
                {required:true,message:'请输入到达城市',trigger:'blur'}
            ],
            departDate:[
                {required:true,message:'请输入出发时间',trigger:'blur'}
            ]
        }
      };
    },
    methods:{
        getCityList(queryString){
            return this.$axios({
                url:'/airs/city',
                params:{name:queryString}
            }).then(res => {
                const list = res.data.data.map(item => {
                    return{
                        // 过滤掉市字
                        value:item.name.replace(/市$/,''),
                        code:item.sort
                    }
                });
                // 过滤掉所有不带有 code 的城市
                // 直接返回过滤没有数据？？
                return list.filter(item => {
                    return item.code
                });
            })
        },
        clearMsg(propName){
            this.$refs.form.clearValidate(propName);
        },
        queryDepartSearch(querystring,callback){
            this.getCityList(querystring).then(list => {
                if(list.length > 0){
                    this.form.departCode = list[0].code;
                }
                 callback(list);
            })
        },
        queryDestSearch(querystring,callback){
            // 这个函数是自动补全的回调函数
            // 用来提供补全的建议数据数组
            // 有两个参数
            // 1. val 是当前输入值
            // 2. 回调函数, 用来将准备好的数组返回出去

            // 准备的数据格式是固定的, 是一个数组
            // 数组里面每一个对象都是一条建议
            // 建议对象里面最重要的一个属性是 value
            // 这个值最终会被显示在列表中
            this.getCityList(querystring).then(list => {
                if(list.length > 0){
                    // 当用户不选择选项时，默认给第一个出现的值（这个第一个出现的值，必然是用户输入框中的值）
                    this.form.destCode = list[0].code;
                }
                callback(list);
            });
        },
        handleDepartSelect(selectVal){
            this.form.departCode = selectVal.code;
        },
        handleDestSelect(selectVal){
            this.form.destCode = selectVal.code;
        },
        search(){
            this.$refs.form.validate().then(isValid => {
                if(isValid){
                    this.isAtHistiry();
                    // 利用编程式导航跳转页面
                    this.$router.push({
                        path:'/ticket/journey',
                        query:this.form
                    })
                }
            }).catch(objNotValid => {
                console.log(objNotValid);
            });
        },
        handleChange(){
            if(this.form.destCity || this.form.departCity){
                let tempCode = this.form.destCode;
                let tempCity = this.form.destCity;

                this.form.destCode = this.form.departCode;
                this.form.destCity = this.form.departCity;
                
                this.form.departCode = tempCode;
                this.form.departCity = tempCity;
            }
        },
        isAtHistiry(){
            let flag = 0;
            let historyList = this.$store.state.history.historyList;
            if(historyList.length > 0){
                // 判重
                for(let i=0;i<historyList.length;i++){
                    if(historyList[i].departCity == this.form.departCity 
                        && historyList[i].destCity == this.form.destCity 
                        && historyList[i].departDate == this.form.departDate){
                            flag = 1;   
                            break;   
                    }
                }
            }
            if(flag == 0){
                // 添加到历史记录list中
                this.$store.commit('history/setHistoryInfo',this.form);
            }
        }
    }
  }
</script>

<style lang="less" scoped>
.form{
    position: relative;
    margin:14px 50px 0 18px;
    text-align: right;
}
.link{
    position: absolute;
    right: -27px;
    top: 20px;
    width: 26px;
    height: 60px;
    border:1px solid #CCCCCC;
    border-left: 0;
    span{
        position: absolute;
        right: -11px;
        top: 20px;
        width: 21px;
        height: 21px;
        color: #fff;
        font-size: 12px;
        line-height: 21px;
        text-align: center;
        border-radius: 2px;
        background-color: #999999;
        cursor: pointer;
    }
}
.el-date-editor.el-input, .el-date-editor.el-input__inner {
    width: 200px !important;
}
.btn{
    width: 200px;
    height: 40px;
    text-align: center;
    i{
        margin-right: 8px;
    }
}
//修改框架内部样式
/deep/.el-form-item__error {
    margin-left: 8px;
}
/deep/.el-form-item__label {
    padding: 0 4px 0 0;
}
</style>